// pages/publish/publish.js
const app = getApp();
const DB = wx.cloud.database()
var that;
var util = require('../../utils/util');
var yun_file_id_arr = [];
Page({
  data: {
    files:[]

  },
  onLoad() {

  },
  ttval(e) {
    console.log(e.detail.value);
    this.setData({
      ttval: e.detail.value
    })
  },
  up_img(item_idx, end_idx) {
    if (item_idx == end_idx) {
      this.add_square();
      yun_file_id_arr = [];
      return
    }
    var files = this.data.files;
    var date = new Date().getTime()
    wx.cloud.uploadFile({
      cloudPath: date + '.png',
      filePath: files[item_idx], // 文件路径
    }).then(res => {
      yun_file_id_arr.push(res.fileID)
      item_idx++;
      this.up_img(item_idx, end_idx)
    }).catch(error => {
      // handle error
    })
  },
  add_square() {
    if (yun_file_id_arr.length == 0) {
      if (this.data.files.length > 0) {
        this.up_img(0, this.data.files.length);
      } else {
        wx.showToast({
          title: '请选择文件',
          icon: 'none'
        })
      }
      return
    }
    var userInfo = wx.getStorageSync('user')
    var data = {
      text: this.data.ttval,
      yun_file_id_arr: yun_file_id_arr,
      nickName: userInfo.nickName,
      avatarUrl: userInfo.avatarUrl,
      time: util.formatTime(new Date()),
      openId: userInfo._openId
    };
    console.log('data', data)
    DB.collection('class_schedule_card').add({
      // data 字段表示需新增的 JSON 数据
      data: data
    }).then(res => {
      console.log(res)
      wx.showToast({
        title: '上传完毕',
      })
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/userinfo/myinfo',
        })
      }, 2000)
    })
  },
  chooseImage: function (e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
      }
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  }
});